import { CanActivate, ExecutionContext, HttpCode, Injectable, UnauthorizedException } from "@nestjs/common";
import type { Observable } from "rxjs";
import type { Request } from "express";
import { jwtHelper } from "src/utils";

// * CanActivate 守卫 https://nest.nodejs.cn/guards
@Injectable()
export class AuthGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest<Request>();
    console.log("🚀 ~ AuthGuard ~ request:",request.route.path, request.path, request.method);
    const whiteList = ["/login", "/register", "/update_password", "/", "/device/sse"]; // 白名单

    if (~whiteList.indexOf(request.path)) return true;
    const token = request.get("token");
    if (!token) throw new UnauthorizedException(); // 返回401
    try {
      await jwtHelper().verifyToken(token);
    } catch (error) {
      console.log("🚀 ~ AuthGuard ~ error:", error);
      throw new UnauthorizedException();
    }
    return true;

    // return new Promise(async (resolve, reject) => {
    //   if (~whiteList.indexOf(request.path)) {
    //     resolve(true);
    //   } else {
    //     try {
    //       const token = request.get("token");
    //       if (!token) throw new UnauthorizedException(); // resolve(false) 直接403
    //       await jwtHelper().verifyToken(token);
    //       resolve(true);
    //     } catch (error) {
    //       console.log("🚀 ~ AuthGuard ~ error:", error);
    //       //  reject(false); // reject(false) 直接500
    //       resolve(false);
    //     }
    //   }
    // });
  }
}
